<!DOCTYPE html>
<html lang="en">
<head>
	<meta http-equiv="X-UA-Compatible" content="IE=edge,Chrome=1"/>
    <meta http-equiv="X-UA-Compatible" content="IE=9"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
	<meta charset="utf-8">
	<title>链式编程-模拟jquery底层代码实现</title>
</head>
<body>
	<button id="btn">按钮</button>
<script type="text/javascript">
	
	(function(window, undefined){
		// 大型开发中，一般使用'_'作为私有对象
		function _$(arguments){
			// 匹配id选择器正则
			var res = /#\w+/;
			// 接受所得的元素
			this.dom;
			if(res.test(arguments[0])){
				this.dom = document.getElementById(arguments[0].substring(1))
			} else {
				throw new Error('arguments is error !')
			}
		}

		Function.prototype.method = function (methodName, fn) {
			this.prototype[methodName] = fn;
			return this;
		}

		_$.prototype = {
			addEvent: function (type, fn) {
				if(window.addEventListener){	//FF
					this.dom.addEventListener(type, fn);
				} else if(window.attachEvent){	//IE
					this.dom.attachEvent('on'+type, fn)
				}
				return this;
			},
			setStyle: function (key, value) {
				this.dom.style[key] = value;
				return this;
			}
		}

		Object.defineProperty(_$.prototype, 'constructor', {
			enumerable: false, //设置能否被枚举
			value: _$
		})

		window.$ = _$;

		_$.onReady = function(fn) {
			// 实例话_$对象，注册到window上
			window.$ = function () {
				return new _$(arguments);
			}

			fn();

			_$.method('addEvent', function () {
				
			}).method('setStyle', function () {

			});
		}


	})(window)

	$.onReady(function(){
		var btn = $("#btn");
		console.log(btn);
		$('#btn').addEvent('click', function () {
			alert('click');
		}).setStyle('background', 'red');
	})

</script>
</body>
</html>